var app = getApp()

var modes = ['loop', 'random', 'single']
make_looper(modes)
const backgroundAudioManager = wx.getBackgroundAudioManager()
var _animation; // 动画实体
var _animationIndex = 0; // 动画执行次数index（当前执行了多少次）
var _animationIntervalId = -1; // 动画定时任务id，通过setInterval来达到无限旋转，记录id，用于结束定时任务
const _ANIMATION_TIME = 10000; // 动画播放一次的时长ms

Page({
  data: {
    songIndex: 0,
    displayList: [],
    name: '',
    author: '寒江雪',
    duration: '',
    songTime: '',
    poster: '',
    status: 'pause',
    mode: 'loop',
    loading: true,
    theme: '#31c27c',
  },

  playItem: function (e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      songIndex: index
    })
    if (this.data.mode === 'single') {
      this.setMode('random')
    }

    this.play(this.data.displayList[index])
  },
  play_pause: function () {
    if (this.data.status == 'play') {
      backgroundAudioManager.pause()
      this.setData({
        status: 'pause'
      })
      this.stopAnimationInterval()
    } else {
      backgroundAudioManager.play()
      this.setData({
        status: 'play'
      })
      this.startAnimationInterval()
    }
  },
  next: function (e) {
    if (this.data.songIndex != (this.data.displayList.length - 1)) {
      this.setData({
        songIndex: this.data.songIndex + 1
      })
    }
    this.setIndex()
    this.play()
  },
  prev: function () {
    if (this.data.songIndex != 0) {
      this.setData({
        songIndex: this.data.songIndex - 1
      })

    }
    this.setIndex()
    this.play()
  },
  play: function () {
    var self = this
    var song = this.data.displayList[this.data.songIndex]
    this.setData({
      name: song.title + ' · ' + song.singerName,
      status: 'play',
      poster: song.cover,
      songIndex: this.data.songIndex
    })
    backgroundAudioManager.duration
    backgroundAudioManager.title = song.title
    backgroundAudioManager.singer = song.singerName
    backgroundAudioManager.coverImgUrl = song.cover
    // 设置了 src 之后会自动播放
    backgroundAudioManager.src = song.url
    //
    backgroundAudioManager.onCanplay(function () {
      setTimeout(() => {
        self.data.songTime = backgroundAudioManager.duration
      }, 500);
    })
    //监听播放进度更新
    backgroundAudioManager.onTimeUpdate(function (res) {
      const t = backgroundAudioManager.currentTime
      self.setData({
        duration: formatTime(self.data.songTime - t),
      })
    })
    //播放结束
    backgroundAudioManager.onEnded(function () {
      self.data.songIndex = self.data.songIndex + 1
      self.play()
    })
    this.startAnimationInterval()

  },
  switchMode: function () {
    this.setData({
      mode: modes.next()
    })
  },

  setIndex: function () {
    if (this.data.mode == "loop") {
      this.data.songIndex = this.data.songIndex
    } else if (this.data.mode == "random") {
      this.data.songIndex = this.data.songIndex = Math.floor(Math.random() * this.data.displayList.length);

    } else {
      this.data.songIndex = this.data.songIndex
    }
  },

  goSearch: function () {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  onLoad: function () {
    this.getPlayList()

  },

  getPlayList: function () {
    const self = this
    wx.request({
      url: 'https://ppt-api.qzlhq.com/ppt/songs/getTopList',
      success(res) {
        self.setData({
          displayList: res.data.result
        })
        self.play()
      },
      fail(res) {
        console.log(res)
      }
    })
  },

  onReady: function () {
    _animationIndex = 0;
    _animationIntervalId = -1;
    this.data.animation = '';
  },
  onShow: function () {

    _animation = wx.createAnimation({
      duration: _ANIMATION_TIME,
      timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0'
    })

    const item = app.globalData.selectedSearchItem
    if (item && item.song.src !== this.data.src) {
      var artist = artists[item.artistIndex]
      this.setArtist(artist)
      this.setData({
        src: item.song.src,
        name: item.song.songname
      })
      app.globalData.selectedSearchItem = null
    }
  },

  /**
   * 实现image旋转动画，每次旋转 120*n度
   */
  rotateAni: function (n) {
    _animation.rotate(120 * (n)).step()
    this.setData({
      animation: _animation.export()
    })
  },

  /**
   * 开始旋转
   */
  startAnimationInterval: function () {
    var that = this;
    that.rotateAni(++_animationIndex); // 进行一次旋转
    _animationIntervalId = setInterval(function () {
      that.rotateAni(++_animationIndex);
    }, _ANIMATION_TIME); // 每间隔_ANIMATION_TIME进行一次旋转
  },

  /**
   * 停止旋转
   */
  stopAnimationInterval: function () {
    if (_animationIntervalId > 0) {
      clearInterval(_animationIntervalId);
      _animationIntervalId = 0;
    }
  },
  onShareAppMessage: function () {
    return {
      title: '笛曲-唱吧寒江雪',
      desc: '幽幽笛声仿若天籁',
      path: '/pages/index/index'
    }
  },
})

function setCurrent(src) {
  var idx = 0
  this.forEach(function (item, index) {
    if (src === item.src) {
      return idx = index
    }
  })
  return idx
}

function make_looper(arr, setCurrent) {

  arr.loop_idx = 0

  arr.current = function (current) {
    if (current) {
      this.loop_idx = setCurrent.call(this, current)
    }
    if (this.loop_idx < 0) {
      this.loop_idx = this.length - 1
    }
    if (this.loop_idx >= this.length) {
      this.loop_idx = 0
    }
    return arr[this.loop_idx]
  }

  arr.next = function () {
    this.loop_idx++
    return this.current()
  }

  arr.prev = function () {
    this.loop_idx--
    return this.current()
  }
}

function formatTime(seconds) {
  var min = ~~(seconds / 60)
  var sec = parseInt(seconds - min * 60)
  return min + ':' + ('00' + sec).substr(-2)
}